<style lang="less">
    @import "change-pass.less";
</style>
<template>
    <div>
        <Card v-show="pubLoaded" class="change-pass">
            <p slot="title">
                <Icon type="key"></Icon>
                <span style="color: #de7264" v-show="title!=''">{{title}}</span><span v-show="title==''">修改密码</span>
            </p>
            <div>
                <Form :label-width="100" :model="editPasswordForm" :rules="passwordValidate" label-position="right"
                      ref="editPasswordForm" style="width:450px">
                    <FormItem label="原密码" prop="oldPass">
                        <Input placeholder="请输入现在使用的密码" type="afspassword" password v-model="editPasswordForm.oldPass"></Input>
                    </FormItem>
                    <FormItem label="新密码" prop="newPass">
                        <Poptip placement="right" trigger="focus" width="250">
                            <Input @on-change="strengthChange" placeholder="请输入新密码" type="afspassword" password
                                   v-model="editPasswordForm.newPass"></Input>
                            <div slot="content" v-bind:class="tipStyle">
                                <span class="words">强度 : {{strength}}</span>
                                <Slider :step="33" style="width:95%" v-model="strengthValue"></Slider>
                                <p style="font-size: 12px;color: #FA8072">密码长度在 [{{this.passRule.minLength}}-{{this.passRule.maxLength}}]之间</p>
                                <p style="font-size: 12px;color: #FA8072"v-for="item in passRule.passRules">
                                    {{item.msg}}
                                </p>
                            </div>
                        </Poptip>
                    </FormItem>
                    <FormItem label="确认新密码" prop="rePass">
                        <Input placeholder="请再次输入新密码" type="afspassword" password v-model="editPasswordForm.rePass"></Input>
                    </FormItem>
                    <FormItem style="text-align: center">
                        <Button :loading="savePassLoading" @click="saveEditPass" type="primary">保存</Button>
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <Button v-show="title==''" @click="cancelEditPass">取消</Button>
                    </FormItem>
                </Form>
            </div>
        </Card>
    </div>
</template>

<script>
    import {changePass} from "@/projects/basic/api/admin/user";
    import {listPassRule} from "@/projects/basic/api/admin/sysParam"
    import axios from "@/libs/request/axios";

    export default {
        name: "change_pass",
        props: {
            title: {
                type: String,
                default: () => {
                    return '';
                }
            }
        },
        data() {
            const valideRePassword = (rule, value, callback) => {
                if (value !== this.editPasswordForm.newPass) {
                    callback(new Error("两次输入密码不一致"));
                } else {
                    callback();
                }
            };
            const passwordValidate = (rule, value, callback) => {
                if (value == this.editPasswordForm.oldPass) {
                    callback(new Error("不能和老密码一致"));
                } else {
                    if(value.length>this.passRule.maxLength||value.length<this.passRule.minLength){
                        callback(new Error('密码长度必须在['+this.passRule.minLength+','+this.passRule.maxLength+']之间'));
                        return
                    }
                    for(let index = 0;index<this.passRule.passRules.length;index++){
                        if(!value.match(this.passRule.passRules[index].reg)){
                            callback(new Error(this.passRule.passRules[index].msg));
                            return ;
                        }
                    }
                    callback();
                }
            };
            return {
                pubKey:'',
                pubLoaded:false,
                savePassLoading: false,
                tipStyle: "password-tip-none",
                strength: "无",
                strengthValue: 0,
                editPasswordForm: {
                    oldPass: "",
                    newPass: "",
                    rePass: ""
                },
                passRulesConstants:{
                    "1":{reg:/[0-9]+/,msg:'密码必须包含数字'},
                    "2":{reg:/[a-z]+/,msg:'密码必须包含小写字母'},
                    "3":{reg:/[A-Z]+/,msg:'密码必须包含大写字母'},
                    "4":{reg:/[^A-Za-z0-9]+/,msg:'密码必须包含特殊字符'}
                },
                passRule:{
                    minLength:6,
                    maxLength:12,
                    rules:['0'],
                    passRules:[]
                },
                passwordValidate: {
                    oldPass: [
                        {
                            required: true,
                            message: "请输入原密码",
                            trigger: "blur"
                        }
                    ],
                    newPass: [
                        {
                            required: true,
                            message: "请输入新密码",
                            trigger: "blur"
                        },
                        {
                            validator:passwordValidate,
                            trigger: "blur"
                        }
                    ],
                    rePass: [
                        {
                            required: true,
                            message: "请再次输入新密码",
                            trigger: "blur"
                        },
                        {
                            validator: valideRePassword,
                            trigger: "blur"
                        }
                    ]
                }
            };
        },
        computed: {

        },
        methods: {
            init() {
            },
            checkStrengthValue(v) {
                // 评级制判断密码强度 最高5
                let grade = 0;
                if (/\d/.test(v)) {
                    grade++; //数字
                }
                if (/[a-z]/.test(v)) {
                    grade++; //小写
                }
                if (/[A-Z]/.test(v)) {
                    grade++; //大写
                }
                if (/\W/.test(v)) {
                    grade++; //特殊字符
                }
                if (v.length >= 10) {
                    grade++;
                }
                return grade;
            },
            strengthChange() {
                if (!this.editPasswordForm.newPass) {
                    this.tipStyle = "password-tip-none";
                    this.strength = "无";
                    this.strengthValue = 0;
                    return;
                }
                let grade = this.checkStrengthValue(this.editPasswordForm.newPass);
                if (grade <= 1) {
                    this.tipStyle = "password-tip-weak";
                    this.strength = "弱";
                    this.strengthValue = 33;
                } else if (grade >= 2 && grade <= 4) {
                    this.tipStyle = "password-tip-middle";
                    this.strength = "中";
                    this.strengthValue = 66;
                } else {
                    this.tipStyle = "password-tip-strong";
                    this.strength = "强";
                    this.strengthValue = 100;
                }
            },
            saveEditPass() {
                let encrypt = new JSEncrypt();
                encrypt.setPublicKey(this.pubKey);
                let params = {
                    password: encrypt.encrypt(this.editPasswordForm.oldPass),
                    newPass: encrypt.encrypt(this.editPasswordForm.newPass),
                    passStrength: this.strength
                };
                this.$refs["editPasswordForm"].validate(valid => {
                    if (valid) {
                        this.savePassLoading = true;
                        changePass(params).then(res => {
                            this.savePassLoading = false;
                            if (res.code === '0000') {
                                this.$Modal.success({
                                    title: "修改密码成功",
                                    content: "修改密码成功，需重新登录",
                                    onOk: () => {
                                        this.$store.dispatch('CLEAN_SESSION').then(() => {
                                            this.$router.push({
                                                name: "login"
                                            });
                                        })
                                    }
                                });
                            }
                        }).catch(() => {
                            this.savePassLoading = false;
                        });
                    }
                });
            },
            cancelEditPass() {
                this.afs.closeTab(this)
            },
            loadRsaPub() {
                axios.request({
                    url: 'pubkey',
                    method: 'get'
                }).then(response => {
                    if (response.code == '0000') {
                        this.pubKey = response.data.pubkey;
                        this.pubLoaded = true;
                    } else {
                        console.log('获取RSA_PUB失败')
                    }
                }).catch(error => {
                        console.log(error)
                    })
            },
            initPassRule(){
                let self = this;
                this.passRule.passRules.splice(0,this.passRule.passRules.length);
                this.passRule.rules.forEach((str)=>{
                    if(self.passRulesConstants[str]){
                        this.passRule.passRules.push(self.passRulesConstants[str]);
                    }
                })
            },
            loadPassRule() {
                listPassRule().then(res=>{
                    if(res.code==='0000'){
                        this.passRule.minLength = res.data.minLength;
                        this.passRule.maxLength = res.data.maxLength;
                        this.passRule.rules.splice(0,this.passRule.rules.length);
                        this.passRule.rules.push(...res.data.rules);
                        console.log(this.passRule)
                        console.log(res.data.rules)
                        this.initPassRule();
                    }else {
                        this.passRule.minLength = 6;
                        this.passRule.maxLength = 12;
                        this.passRule.rules.splice(0,this.passRule.rules.length);
                        this.initPassRule();
                    }
                }).catch(()=>{
                    this.passRule.minLength = 6;
                    this.passRule.maxLength = 12;
                    this.passRule.rules.splice(0,this.passRule.rules.length);
                    this.initPassRule();
                });
            }
        },
        created() {
            this.loadRsaPub();
            this.loadPassRule();
        }
    };
</script>
